/**
 * https://leetcode-cn.com/problems/minesweeper/submissions/
 * @param {character[][]} board
 * @param {number[]} click
 * @return {character[][]}
 */
 var updateBoard = function(board, click) {
  const rows = board.length;
  const cols = board.length ? board[0].length : 0;

  function invalid(row, col) {
      return row < 0 || col < 0 || row > (rows - 1) || col > (cols - 1);
  }
  
  function countMines(r, c) {
      const m = [-1,0,1];
      let count = 0;
      for (let i = 0; i < 3; i++) {
          for (let j = 0; j < 3; j++) {
              const row = r + m[i];
              const col = c + m[j];
              // 检查越界
              if (invalid(row, col)) {
                  continue;
              }
              if (board[row][col] === 'M') {
                  count++;
              }
          }
      }
      return count;
  }

  function dig(r, c) {
      // terminator 检查越界
      if (invalid(r, c)) {
          return;
      }
      // dead
      if (board[r][c] === 'M') {
          board[r][c] = 'X';
          return;
      }
      // process && drill down
      if (board[r][c] === 'E') {
          const count = countMines(r, c);
          if (!count) {
              board[r][c] = 'B';
              dig(r - 1, c - 1);
              dig(r - 1, c);
              dig(r - 1, c + 1);
              dig(r, c - 1);
              dig(r, c + 1);
              dig(r + 1, c - 1);
              dig(r + 1, c);
              dig(r + 1, c + 1);
          } else {
              board[r][c] = count + "";
          }
      }
  }
  dig(...click);
  return board;
};